<?
require('../bootstrap.php');
require('../includes/site_config.php');

// Functions for handling index position
require_once('includes/page_index_handling.php');

auth_redirect();

$author = get_author();
$errors = array();
$new_author = false;
$type = 'new';

if (isset($_GET['id'])) {
	$type = 'edit';
	$res = $db->get_result("SELECT * FROM $pages_table WHERE `id` = $_GET[id]");
	
	if (!isset($_POST['submit'])) {
		$_POST = $res[0];
	}
	
	// Relative position in menu (calculated)
	$_POST['menu_pos'] = page_menuPos($_GET['id']);
	
	// If current author is different from the previous author
	if ($res[0]['author_id'] != $author['id']) {
		$new_author = true;
	}
	
}

if (isset($_POST['submit'])) {

	$_POST['title'] = escape($_POST['title']);
	
	if ($_POST['title'] == '') {
		$errors[] = "Titel skal udfyldes";
	}	
	/*
	if (!isset($_POST['index']) || $_POST['index'] == '') {
		$_POST['index'] = page_nextIndex();
	} else {
		if (is_numeric($_POST['index']) == false) {
			$errors[] = "Indeks skal være et nummer";
		}
	}
	*/

	if ($_POST['title'] != '') {

		// Replace spaces with underscore
		$name = str_replace(" ", "_", $_POST['title']);
		// Replace danish characters with thier english representation
		$name = str_replace("æ", "ae", $name);
		$name = str_replace("ø", "oe", $name);
		$name = str_replace("å", "aa", $name);
		
		if (isset($_POST['id'])) {
			if ($db->count($pages_table, "id", "`name` = '$name'") != 0) {
				$errors[] = "Navnet på siden er allerede i brug";
			}
		}
	}

	if (count($errors) <= 0) {
		
		if (isset($_GET['id']) && $_GET['id'] != '') {
			$r = $db->execute("UPDATE $pages_table SET `name` = '$name', title = '$_POST[title]',
				`text` = '$_POST[text]', updated_at = NOW() WHERE id = $_GET[id]");
			
		} else {
			$index = page_nextIndex();
			$str = "INSERT INTO $pages_table (`name`, `title`, `index`, `text`, updated_at, author_id)
				VALUES ('$name', '$_POST[title]', $index, '$_POST[text]', NOW(), $author[id])";
			$r = $db->execute($str);		
		}
		
		if ($r == 1) {
			$session->set('page_saved', true);
			redirect('pages.php');
		}
	}
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<title>KomitCMS | <? echo ($type == 'new') ? 'Ny' : 'Ret' ?> side</title>
		<meta http-equiv="content-type" content="text/html;charset=utf-8" />
		<meta http-equiv="Content-Style-Type" content="text/css" />
		<link rel="stylesheet" type="text/css" href="../stylesheet/style.css" />
		
		<script type="text/javascript" src="../javascript/tiny_mce/tiny_mce.js"></script>
		<script type="text/javascript">
			tinyMCE.init({
				// General options
				mode : "textareas",
				theme : "advanced",
				plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount",

				// Theme options
				theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
				theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|preview,|,forecolor,backcolor",
	
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				theme_advanced_statusbar_location : "bottom",
				theme_advanced_resizing : true,

				// Example content CSS (should be your site CSS)
				content_css : "css/content.css",

				// Drop lists for link/image/media/template dialogs
				template_external_list_url : "lists/template_list.js",
				external_link_list_url : "lists/link_list.js",
				external_image_list_url : "lists/image_list.js",
				media_external_list_url : "lists/media_list.js",

				// Replace values for the template plugin
				template_replace_values : {
					username : "Some User",
					staffid : "991234"
				}
			});
		</script>
	
	<!--
		<script src="../javascript/nicEdit.js" type="text/javascript"></script>
		<script type="text/javascript">
			window.onload = function () {
				new nicEditor({iconsPath: '../javascript/nicEditorIcons.gif'}).panelInstance('editor');
			}
		</script>
	-->
	</head>
	<body>
		<div class="AUI_Header">
			<h1>Admin</h1>
			<? include 'menu.php' ?>
		</div>
		
		<div class="AUI_Content">
		<h2><? echo ($type == 'new') ? 'Ny' : 'Ret' ?> side</h2>
		
		<? if ($new_author == true) { ?>
			<div class="UI_Notice_Info">
				Du er ikke denne sides oprindelige forfatter!
			</div>
		<? } ?>
		
		<? if (count($errors) > 0) { ?>
			<div class="UI_Errors">
				<ul>
					<? foreach ($errors as $e) { ?>
						<li><? echo $e ?></li>
					<? } ?>
				</ul>
			</div>
		<? } ?>
		
		<form method="post">
		<table class="UI_Editor" cellspacing="0" cellpadding="0">
			<tr>
				<td class="label">Titel<br/>
					<small>(Obligatorisk)</small></td>
				<td><input type="text" name="title" value="<?= get_value($_POST, 'title') ?>" /></td>
			</tr>
			<? if ($type == 'edit') { ?>
			<tr>
				<td class="label">
					Indeks<br/>
					<small>(Sidens placering i menuen)</small>					
				</td>
				<td>
					<input type="text" readonly="1" value="<?= get_value($_POST, 'menu_pos')?>" 
						style="background-color:#eee" />
				</td>		
			</tr>
			<? } ?>
			<tr class="tallrow">
				<td class="label">Indhold</td>
				<td>
					<textarea name="text" id="editor" style="width: 400px; height:200px;">
						<?= get_value($_POST, 'text') ?>
					</textarea>
				</td>
			</tr>
			<tr>
				<td />
				<td>
					<div class="divider" />
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<div class="buttons">
						<input type="submit" name="submit" value="Gem">
						<input type="button" value="Annuller" onclick="document.location.href='pages.php'"/>
					</div>
				</td>
			</tr>
		</table>
		</form>
		</div>
	</body>
</html>